﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;
using Report.Model;

namespace Report.Forms
{
    public partial class FrmAddResultCurve
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public POINT(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }
        }
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool GetCursorPos(out POINT pt);
        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)]
        private static extern IntPtr FindWindow(string className, string windowName);

        private readonly MultiavityReportManager1 _manager;
        public FrmAddResultCurve()
        {
            InitializeComponent();
            Resources.MergedDictionaries.Add(ReportCommon.GetLan);
            _manager = MultiavityReportManager1.Create();
        }

        private void FrmAddCurve_OnLoaded(object sender, RoutedEventArgs e)
        {
            var datas = _manager.DataInfo;
            var xs = datas.Where(d => d.DataNo == 10040);
            CbbX.ItemsSource = xs;
            CbbX.DisplayMemberPath = "Text";
            CbbX.SelectedValuePath = "DataNo";
            _initY();
        }

        private void _initY()
        {
            foreach (var control in WpYs.Children)
            {
                var cb = control as CheckBox;
                cb.Checked -= Cb_Checked;
            }
            WpYs.Children.Clear();
            var sx = CbbX.SelectedValue?.ToInt() ?? 0;
            var ys = _manager.ResultInfo.Where(d => d.DataNo != 10034 && d.DataNo != 10040 && d.DataType != DataType.String && d.DataType != DataType.DateTime);
            var style = Resources["CheckBoxStyle"] as Style;
            foreach (var y in ys)
            {
                var cb = new CheckBox { Content = y.Text, Margin = new Thickness(5, 0, 0, 0), Tag = y.DataNo };
                cb.Checked += Cb_Checked;
                if (style != null) cb.Style = style;
                WpYs.Children.Add(cb);
            }
        }

        private void Cb_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox cb)
            {
                if (cb.IsChecked.HasValue && cb.IsChecked.Value)
                {
                    var c = 0;
                    foreach (var control in WpYs.Children)
                    {
                        var cbc = control as CheckBox;
                        if (cbc?.IsChecked != null && cbc.IsChecked.Value)
                        {
                            c++;
                        }
                    }

                    if (c > 2) cb.IsChecked = false;
                }
            }
        }

        private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void BtnOk_OnClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TxtName.Text)) return;

            var ys = new List<Axis>();
            foreach (var control in WpYs.Children)
            {
                var cb = control as CheckBox;
                if (cb?.IsChecked != null && cb.IsChecked.Value)
                {
                    ys.Add(new Axis{Id = cb.Tag.ToInt()});
                }
            }
            if(ys.Count ==0) return;
            // ReSharper disable once PossibleInvalidOperationException
            var r = _manager.AddCurves(TxtName.Text, RbShow.IsChecked.Value, new Axis { Id = CbbX.SelectedValue.ToInt() }, ys.ToArray());
            if (r < 0)
            {
                MyMessageBox.Show(this,Resources.GetLanguageValue("NameIsExist"));
                return;
            }
            DialogResult = true;
            Close();
        }

        private void CbbX_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (CbbX.SelectedValue != null)
            //{
            //    _initY();
            //}
        }

        private void TxtName_OnGotFocus(object sender, RoutedEventArgs e)
        {
            var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Keyboard.exe");
            if (!File.Exists(file)) return;
            POINT pt = new POINT();
            GetCursorPos(out pt);
            Process.Start(file, $"{pt.X} {pt.Y}");
        }

        private void TxtName_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (_isOpen()) return;
            if (sender is FrameworkElement fe)
            {
                fe.Focus();
            }
        }

        private bool _isOpen()
        {
            var name = "KeyboardWindow";
            var ptr = FindWindow(null, name);
            return ptr != IntPtr.Zero;
        }
    }
}
